<div class="layuimini-main" id="Access-add">
    <style>

        .defcenter {
            text-align: center;
        }
    </style>

    <div class="layui-card">
        <div class="layui-card-body" style="padding-top: 40px;">
            <div class="layui-carousel" id="stepForm" lay-filter="stepForm" style="margin: 0 auto;">
                <div carousel-item>
                    <div>
                        <form class="layui-form" style="margin: 0 auto;max-width: 800px;padding-top: 40px;">
                            <div class="layui-card">
                                <div class="layui-card-header"><h2>选择需要操作的门</h2></div>
                                <div class="layui-card-body">
                                    <div>
                                        <table class="layui-hide" id="AccessDeviceTable" lay-filter="AccessDeviceTableFilter"></table>
                                    </div>
                                    <div class="layui-panel defcenter">
                                        <button class="layui-btn" lay-submit lay-filter="btnSelectDoorOver">
                                            下一步
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div>
                        <form class="layui-form" style="margin: 0 auto;max-width: 800px;padding-top: 40px;">
                            <div class="layui-card">
                                <div class="layui-card-header"><h2>选择需要操作的人员</h2></div>
                                <div class="layui-card-body">
                                    <div>
                                        <table class="layui-hide" id="AccessPeoplePageTable" lay-filter="AccessPeoplePageTableFilter"></table>
                                    </div>
                                    <div class="layui-panel defcenter">
                                        <button type="button" class="layui-btn layui-btn-primary" id="btnSelectPeopleAll"><i class="layui-icon">&#xe615;</i>选择所有</button>
                                        <button type="button" class="layui-btn layui-btn-primary" id="btnSearchPeople"><i class="layui-icon">&#xe615;</i>筛选</button>
                                        <button type="button" class="layui-btn layui-btn-primary pre">上一步</button>
                                        <button class="layui-btn" lay-submit lay-filter="btnSelectPeopleOver">下一步</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div>
                        <form class="layui-form" style="margin: 0 auto;max-width: 800px;padding-top: 40px;">
                            <div class="layui-card">
                                <div class="layui-card-header"><h2>设置人员的权限详情</h2></div>
                                <div class="layui-card-body">

                                    <div class="layui-form-block">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">开门时段</label>
                                            <div class="layui-input-block">

                                                <select name="TimeGroupID" lay-verify="">
                                                    <option value="1" selected>时段1</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">人员角色</label>
                                            <div class="layui-input-block">
                                                <select name="EmployeeRoot" lay-verify="">
                                                    <option value="0" selected>用户</option>
                                                    <option value="1">管理员</option>
                                                    <option value="2">黑名单</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">有效期限制</label>
                                            <div class="layui-input-block">
                                                <select name="devicePassTimeOver" lay-verify="">
                                                    <option value="1" selected>受限制</option>
                                                    <option value="0">无限制</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">起始时间</label>
                                            <div class="layui-input-block">
                                                <input type="text" maxlength="20" name="DevicePassStart" lay-verify="required" autocomplete="off" class="layui-input">
                                            </div>
                                        </div>
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">截至时间</label>
                                            <div class="layui-input-block">
                                                <input type="text" maxlength="20" name="DevicePassEnd" lay-verify="required" autocomplete="off" class="layui-input">
                                            </div>
                                        </div>
                                        <div class="layui-card">
                                            <div class="layui-card-header">通行次数</div>
                                            <div class="layui-card-body">

                                                <div style="margin-left: 10px; border-right-width: 0px; border-right-style: solid; margin-bottom: 20px; margin-right: 10px; ">
                                                    <div id="devicePassNumber" name="devicePassNumber"></div>
                                                </div>
                                                <h2 class="layui-colla-title">（0 无限通行次数，其他：通行次数）</h2>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-panel defcenter">
                                        <button type="button" class="layui-btn layui-btn-primary pre">上一步</button>
                                        <button class="layui-btn layui-btn-primary" lay-submit lay-filter="btnAddAccess">允许开门</button>
                                        <button class="layui-btn layui-btn-danger data-delete-btn" lay-submit lay-filter="btnDeleteAccess">禁止开门</button>

                                    </div>

                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>

    layui.use(['form', 'laydate', 'miniPage', 'table', 'faceAPI', 'step', 'slider'], function () {
        var form = layui.form,
            layer = layui.layer,
            table = layui.table,
            step = layui.step,
            $ = layui.$;
        var slider = layui.slider;
        var faceAPI = layui.faceAPI;
        var laydate = layui.laydate;
        var miniPage = layui.miniPage;


        var TimeGroups = [];
        for (var i = 1; i < 65; i++) {
            var sItem = ' <option value="' + i + '" ';
            if (i == 1) sItem += ' selected';
            sItem += '> 时段' + i + '</option> ';
            TimeGroups.push(sItem);
        }
        $('[name=TimeGroupID]').html(TimeGroups.join(''));

        /**
         * 初始化表单，要加上，不然刷新部分组件可能会不加载
         */
        form.render();

        //渲染
        var devicePassNumberValue = 0;
        var sldevicePassNumber = slider.render({
            elem: '[name="devicePassNumber"]',  //绑定元素
            min: 0,
            max: 1000,
            value: 0,
            input: true,
            setTips: function (value) { //自定义提示文本
                if (value == 0) {
                    return '无限制通讯次数';
                } else

                    return value + '次';
            },
            change: function (data) {
                devicePassNumberValue = data;
            }

        });

        //执行一个laydate实例
        laydate.render({
            elem: '[name="DevicePassStart"]', //指定元素
            type: 'datetime'
        });
        //执行一个laydate实例
        laydate.render({
            elem: '[name="DevicePassEnd"]', //指定元素
            type: 'datetime'
        });
        $('[name="DevicePassStart"]').attr("value", dayjs().format("YYYY-MM-DD") + ' 00:00:00');
        $('[name="DevicePassEnd"]').attr("value", dayjs().add(1, 'Year').format("YYYY-MM-DD") + ' 23:59:59');

        step.render({
            elem: '#stepForm',
            filter: 'stepForm',
            width: '100%', //设置容器宽度
            stepWidth: '800px',
            height: '650px',
            stepItems: [{
                title: '选择门'
            }, {
                title: '选择人员'
            }, {
                title: '设置细节'
            }]
        });

        // 当前弹出层，防止ID被覆盖
        var parentIndex = layer.index;

        faceAPI.AccessAddPageResult = null;

        form.on('submit(btnSelectDoorOver)', function (data) {
            var checkStatus = table.checkStatus('AccessDeviceTable')
                , data = checkStatus.data;
            if (data.length == 0) {
                layer.open({
                    title: '提示'
                    , content: '请勾选需要进行授权操作的门'
                });
                return false;
            }

            step.next('#stepForm');
            return false;
        });



        $('.pre').click(function () {
            step.pre('#stepForm');
        });

        $('.next').click(function () {
            step.next('#stepForm');
        });


        form.on('submit(btnAddAccess)', function (data) {
            PostAccess(1, data.field);

            return false;
        });
        form.on('submit(btnDeleteAccess)', function (data) {
            PostAccess(0, data.field);
            //step.next('#stepForm');
            return false;
        });

        //提交权限--自选人员
        function PostAccess(iAccessType, oAccessDetail) {



            //门列表
            var doorCheckStatus = table.checkStatus('AccessDeviceTable')
                , doorData = doorCheckStatus.data;
            var DeviceIDs = [];
            doorData.forEach(function (item, index) { DeviceIDs.push(item.id); });

            if (bSelectPeopleAll) {
                PostAccess_ALL(iAccessType, DeviceIDs, oAccessDetail);
                return;
            }


            //人员列表
            var peopleCheckStatus = table.checkStatus('AccessPeoplePageTable')
                , peopleData = peopleCheckStatus.data;
            var PeopleIDs = [];
            peopleData.forEach(function (item, index) { PeopleIDs.push(item.id); });

            var postPar = { DeviceIDs, PeopleIDs, AccessType: iAccessType, DevicePassNumber: devicePassNumberValue };
            $.extend(postPar, oAccessDetail);
            //console.log(postPar);
            var loadIndex = 0;
            loadIndex = layer.load(1, { shade: [0.6, '#e2e2e2'] }); //0.1透明度的白色背景
            faceAPI.Ajax({
                type: 'Post',
                data: postPar,
                url: '/api/DeviceAccess/Add',
                success: function (result) {
                    layer.close(loadIndex);
                    if (result.result == false) {
                        layer.alert(result.error, { icon: 2 });
                    }
                    else {
                        //$.extend(result.content, postdata);
                        faceAPI.AccessAddPageResult = result;

                        layer.close(parentIndex);
                    }
                }
            });
        }

        //提交所有人员的权限
        //iAccessType 1--授权；0--删除权限
        function PostAccess_ALL(iAccessType, DeviceIDs, oAccessDetail) {
            var postPar = { DeviceIDs, AccessType: iAccessType, DevicePassNumber: devicePassNumberValue };
            $.extend(postPar, oAccessDetail);
            var loadIndex = 0;
            loadIndex = layer.load(1, { shade: [0.6, '#e2e2e2'] }); //0.1透明度的白色背景
            faceAPI.Ajax({
                type: 'Post',
                data: postPar,
                url: '/api/DeviceAccess/Add_AllPeople',
                success: function (result) {
                    layer.close(loadIndex);
                    if (result.result == false) {
                        layer.alert(result.error, { icon: 2 });
                    }
                    else {
                        //$.extend(result.content, postdata);
                        faceAPI.AccessAddPageResult = result;

                        layer.close(parentIndex);
                    }
                }
            });
        };
        /*
        function GetPeopleIDByPage(iPageIndex, iSize, callblack, accessContext) {
            faceAPI.Ajax({
                type: 'Post',
                data: { pageIndex: iPageIndex, pageSize: iSize},
                url: '/api/People/GetPeopleIDList',
                success: function (result) {
                    layer.close(loadIndex);
                    if (result.result == false) {
                        layer.alert(result.error, { icon: 2 });
                    }
                    else {
                        debugger;
                        accessContext.PeopleIDs = result.content;
                        callblack(accessContext);
                    }
                }
            });
        }
        */
        //加载门列表
        table.render({
            height: 450,
            elem: '#AccessDeviceTable',
            //**************************异步请求开始***********************
            url: 'api/FaceDeviceNew/GetDeviceTable',
            method: 'post',
            headers: {
                Authorization: "Bearer " + faceAPI.GetJWTToken()
            },//增加Token验证头
            request: {
                pageName: 'pageIndex', //页码的参数名称，默认：page
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                if (res.errCode == 0) {
                    var data = res.content;
                    var ret = {
                        "code": res.errCode, //解析接口状态
                        "msg": res.error, //解析提示文本
                        "count": data.totalCount, //解析数据长度
                        "data": data.dataList //解析数据列表
                    };
                    return ret;

                } else {
                    return {
                        "code": 0, //解析接口状态
                        "msg": '', //解析提示文本
                        "count": 0, //解析数据长度
                        "data": [] //解析数据列表
                    };
                }
            },
            cols: [[
                { type: "checkbox", width: 50 },
                { field: 'deviceID', width: 180, title: 'SN', sort: true },
                { field: 'deviceName', title: '名称', sort: true }
            ]],
            limits: [100, 200, 500, 1000],
            limit: 100,
            page: true,
            skin: 'line'
        });

        //选择所有人员

        var bSelectPeopleAll = false;
        $('#btnSelectPeopleAll').click(function () {
            bSelectPeopleAll = true;
            step.next('#stepForm');
        });

        form.on('submit(btnSelectPeopleOver)', function (data) {
            var checkStatus = table.checkStatus('AccessPeoplePageTable')
                , data = checkStatus.data;
            if (data.length == 0) {
                layer.open({
                    title: '提示'
                    , content: '请勾选需要进行授权操作的人员'
                });
                return false;
            }
            bSelectPeopleAll = false;
            step.next('#stepForm');
            return false;
        });

        //筛选
        $('#btnSearchPeople').click(function () {
            var content = miniPage.getHrefContent('page/People/search.html');
            var openWH = miniPage.getOpenWidthHeight();

            var index = layer.open({
                title: '搜索人员',
                type: 1,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: [openWH[0] + 'px', openWH[1] + 'px'],
                offset: [openWH[2] + 'px', openWH[3] + 'px'],
                content: content,
                end: function (layero, index) {

                    var rst = faceAPI.PeopleSearchPageResult;
                    if (rst != null && rst.result) {
                        table.reload('AccessPeoplePageTable', {
                            page: {
                                curr: 1
                            }, where: faceAPI.PeopleSearchPageResult.field
                        }, 'data');
                    };

                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        });


        //加载人员列表
        table.render({
            height: 450,
            elem: '#AccessPeoplePageTable',
            //**************************异步请求开始***********************
            url: 'api/PeopleNew/GetPeopleTableMini',
            method: 'post',
            headers: {
                Authorization: "Bearer " + faceAPI.GetJWTToken()
            },//增加Token验证头
            request: {
                pageName: 'pageIndex', //页码的参数名称，默认：page
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                if (res.errCode == 0) {
                    var data = res.content;
                    var ret = {
                        "code": res.errCode, //解析接口状态
                        "msg": res.error, //解析提示文本
                        "count": data.totalCount, //解析数据长度
                        "data": data.dataList //解析数据列表
                    };
                    return ret;

                } else {
                    return {
                        "code": 0, //解析接口状态
                        "msg": '', //解析提示文本
                        "count": 0, //解析数据长度
                        "data": [] //解析数据列表
                    };
                }

            },
            cols: [[
                { type: "checkbox", width: 50 },
                { field: 'code', width: 140, title: '人员编号', sort: true },
                { field: 'name', width: 160, title: '姓名', sort: true },
                {//人员识别凭证
                    field: 'card', width: 100, title: '凭证', sort: false,
                    templet: function (d) {
                        var sBuf = [];
                        if (d.card > 0) {
                            sBuf.push('<i class="PeopleAccessKey fa fa-credit-card"  typeTitle="卡号"  type="text"  value = "' + d.card + '"></i>');
                        }
                        if (d.photo != null && d.photo.length > 0) {
                            sBuf.push('<i class="PeopleAccessKey fa fa-child" typeTitle="照片" type="image" value = "' + d.photo + '"></i>');
                        }
                        if (d.pin != null && d.pin.length > 0) {
                            sBuf.push('<i class="PeopleAccessKey fa fa-at" typeTitle="密码" type="text" value = "' + d.pin + '"></i>');
                        }

                        return sBuf.join(' ');
                    }
                }

            ]],
            limits: [100, 200, 300, 500],
            limit: 300,
            page: true,
            skin: 'line',
            done: function (res, curr, count) {
                //绑定事件
                if (res.count > 0) {
                    //lay-filter="PeoplePageTableFilter"
                    bindPeopleAccessKey();
                }
            }
        });

        function bindPeopleAccessKey() {
            $("[lay-id=AccessPeoplePageTable] i.PeopleAccessKey").mouseenter(AccessKey_mouseenter);
            $("[lay-id=AccessPeoplePageTable] i.PeopleAccessKey").mouseleave(() => {
                if (iMouseenter_TipIndex > 0)
                    layer.close(iMouseenter_TipIndex);
            });
        }

        table.on('sort(AccessPeoplePageTableFilter)', function (obj) {
            bindPeopleAccessKey();

        });

        // 在线离线状态显示提示框
        var iMouseenter_TipIndex = 0;
        function AccessKey_mouseenter() {
            var that = this;
            if (iMouseenter_TipIndex > 0)
                layer.close(iMouseenter_TipIndex);
            var spn = $(that);
            var sType = spn.attr("type");
            var stypeTitle = spn.attr("typeTitle");
            var sValue = spn.attr("value");
            var sHtml = '';//'<div class="layui-card">';
            //sHtml = sHtml + '<div class="layui-card-header">' + stypeTitle + '</div>';
            //sHtml = sHtml + '<div class="layui-card-body">';



            var par = { area: ['240px', '160px'] };
            //debugger;
            if (sType == "text") {

                sHtml = '<h2>' + stypeTitle + '</h2>' + '<h3>' + sValue + '</h3>';
            }
            else {
                par.area[0] = '260px';
                par.area[1] = '380px';
                sHtml = '<h2>' + stypeTitle + '</h2>' + '<img id="showPeopleImg" src="' + sValue + '" width="240"/>';
            }


            //sHtml = sHtml + '</div></div>';

            //console.log(sHtml);
            iMouseenter_TipIndex = layer.tips(sHtml, that, par);
        }

    });

</script>